<template>
    <div>
      <pro-table
        :columns="columns"
        :request="(params)=>fetchUsers(params)"
        row-key="id"
        :pagination="pagination"
        :action-ref="setActionRef"
        :scroll="{ x: 2400 }"
        header-title=""
        :search="{ collapsed:false }"
      >
        <template #option-render="{ dom }">
          <a-button v-auth="'exportUserBtn'" type="primary" @click="exportdata">导出</a-button>
          <a-button v-auth="'addUserBtn'" type="primary" @click="handleAdd">添加</a-button>
          <component :is="dom[1]" />
          <component :is="dom[0]" />
        </template>
        <template #action="{ record }">
       
          <a-button v-auth="'eidtUserBtn'" type="text" @click="handleEdit(record)">编辑</a-button>
          <a-button v-auth="'detailUserBtn'" type="text" @click="handleDetail(record.id)">详情</a-button>
          <a-popconfirm  content="确认删除么"  @ok="handleDelete(record.id)">
            <a-button v-auth="'delUserBtn'" type="text" status="danger" >删除</a-button>
          </a-popconfirm>
        
        </template>
      </pro-table>
      <a-modal :width="1200" v-model:visible="detailVisible" title="用户详情">
        <a-descriptions bordered>
          <a-descriptions-item label="姓名">{{ detail.name }}</a-descriptions-item>
          <a-descriptions-item label="CID">{{ detail.cid }}</a-descriptions-item>
          <a-descriptions-item label="手机号">{{ detail.phone }}</a-descriptions-item>
          <a-descriptions-item label="地址">{{ detail.address }}</a-descriptions-item>
          <a-descriptions-item label="签约状态">{{ detail.signStatus === 0 ? '未签约' : '已签约' }}</a-descriptions-item>
          <a-descriptions-item label="用户意向">{{ detail.intention }}</a-descriptions-item>
          <a-descriptions-item label="状态">{{ detail.status === 0 ? '启用' : '禁用' }}</a-descriptions-item>
          <a-descriptions-item label="备注">{{ detail.remark }}</a-descriptions-item>
          <a-descriptions-item label="标签">{{ detail.tagName }}</a-descriptions-item>
          <a-descriptions-item label="所属服务管家">{{ detail.createUserName }}</a-descriptions-item>
        </a-descriptions>
        <tabList :username="detail.phone" address=""></tabList>
      </a-modal>
      <a-modal v-model:visible="formVisible" :title="formTitle">
        <a-form ref="formRef" :model="formData" layout="vertical">
          <a-form-item label="姓名" :rules="[{ required: true, message: '请输入姓名' }]">
            <a-input v-model="formData.name" placeholder="请输入姓名" />
          </a-form-item>
          <a-form-item label="手机号" :rules="[{ required: true, message: '请输入手机号' }]">
            <a-input v-model="formData.phone" placeholder="请输入手机号" />
          </a-form-item>
          <!-- <a-form-item label="省">
            <a-input v-model="formData.province" placeholder="请输入省" />
          </a-form-item>
          <a-form-item label="市">
            <a-input v-model="formData.city" placeholder="请输入市" />
          </a-form-item>
          <a-form-item label="区">
            <a-input v-model="formData.county" placeholder="请输入区" />
          </a-form-item> -->
          <a-form-item label="地址">
            <a-textarea v-model="formData.address" placeholder="请输入地址" />
          </a-form-item>
          <a-form-item label="签约状态">
            <a-select v-model="formData.signStatus">
              <a-option :value="0">未签约</a-option>
              <a-option :value="1">已签约</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="用户意向">
            <a-input v-model="formData.intention" placeholder="请输入用户意向" />
          </a-form-item>
          <a-form-item label="状态">
            <a-select v-model="formData.status">
              <a-option :value="0">启用</a-option>
              <a-option :value="1">禁用</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="备注">
            <a-textarea v-model="formData.remark" placeholder="请输入备注" />
          </a-form-item>
          <a-form-item label="标签">
            <a-tree-select placeholder="请选择用户标签" :field-names="{ key: 'id', title: 'name' }"
                  v-model="formData.tagIdList" multiple :data="tagList">
                </a-tree-select>
          </a-form-item>
        </a-form>
        <template #footer>
          <a-button @click="formVisible = false">取消</a-button>
          <a-button type="primary" @click="handleSubmit">提交</a-button>
        </template>
      </a-modal>
    </div>
  </template>
  
  <script lang="ts">
  import { defineComponent, onMounted, ref, Ref } from 'vue';
  import {
    getUserList,
    deleteUser,
    getUserDetail,
    saveUser
  } from '@/api/user';
  import { FormInstance } from '@arco-design/web-vue';
import { getTagList } from '@/api/tag';
import tabList from "@/components/TabList/index.vue"
  
  export default defineComponent({
    components:{
      tabList
    },
    name: 'UserPage',
    setup() {
      const formRef = ref<FormInstance | null>(null);
      const columns = [
        { title: '用户ID', dataIndex: 'id' ,hideInSearch: true},
        { title: 'CID', dataIndex: 'cid' ,ellipsis:true},
        { title: '用户姓名', dataIndex: 'name' },
        { title: '用户手机号', dataIndex: 'phone' },
        { title: '用户地址', dataIndex: 'address',hideInSearch: true },
        { title: '用户标签', dataIndex: 'tagName' ,hideInSearch: true},
        { title: '用户意向', dataIndex: 'intention',hideInSearch: true },
        { title: '是否签约', dataIndex: 'signStatus',hideInSearch: true, valueEnum: {
            1: { text: '是', status: 'Success' },
            0: { text: '否', status: 'Default' },
          }, },
        { title: '创建时间', dataIndex: 'createTime',hideInSearch: true },
        { title: '所属管家', dataIndex: 'createUserName',hideInSearch: true },
        {
          title: '状态',
          dataIndex: 'status',
          valueEnum: {
            0: { text: '启用', status: 'Success' },
            1: { text: '禁用', status: 'Default' },
          },
        },
        { title: '备注', dataIndex: 'remark', hideInSearch: true },
        {
          title: '操作',
          dataIndex: 'action',
          slotName: 'action',
          hideInSearch: true,
          fixed: 'right',
          width: 300
        },
      ];

      const tagList = ref([]);
  
      const actionRef = ref();
  
      const setActionRef = (ref: Ref) => {
        actionRef.value = ref;
      };
  
      const onReload = () => {
        if (actionRef.value) {
          actionRef.value.reload();
        }
      };
  
      const pagination = ref({
        current: 1,
        pageSize: 10,
        total: 0,
      });
  
      const detail = ref({
        cid:'',
        name: '',
        phone: '',
        province: '',
        city: '',
        county: '',
        address: '',
        signStatus: 0,
        intention: '',
        status: 0,
        remark: '',
        tagName: '',
        createUserName: ''
      });
  
      const detailVisible = ref(false);
  
      const formVisible = ref(false);
      const formTitle = ref('添加用户');
      const formData = ref({
        id: undefined,
        name: '',
        phone: '',
        province: '',
        city: '',
        county: '',
        address: '',
        signStatus: 0,
        intention: '',
        status: 0,
        remark: '',
        tagIdList: [] as number[],
      });
  
      const fetchUsers = async (params: {
      }) => {
        const response = await getUserList(params);
        pagination.value.total = response.data.total;
        return {
          data: response.data.list,
          success: true,
          total: response.data.total,
        };
      };
  
      const handleDelete = async (id: number) => {
        await deleteUser(id);
        onReload();
      };
  
      const handleDetail = async (id: number) => {
        const response = await getUserDetail(id);
        detail.value = response;
        detailVisible.value = true;
      };
  
      const handleAdd = () => {
        formTitle.value = '添加用户';
        formData.value = {
          id: undefined,
          name: '',
          phone: '',
          province: '',
          city: '',
          county: '',
          address: '',
          signStatus: 0,
          intention: '',
          status: 0,
          remark: '',
          tagIdList: [],
        };
        formVisible.value = true;
      };
  
      const handleEdit = async (record: any) => {
        formTitle.value = '编辑用户';
        const deatil =  await getUserDetail(record.id)
        formData.value = { ...deatil };
        formVisible.value = true;
      };
  
      const handleSubmit = async () => {
        try {
          await formRef.value?.validate();
          await saveUser(formData.value);
          formVisible.value = false;
          onReload();
        } catch (error) {
          console.error('表单校验失败', error);
        }
      };
      onMounted( async ()=>{
        const list = await getTagList({ type: 3 });
        tagList.value = list.data
      })
      const  exportdata = () =>{
        window.open(`${import.meta.env.VITE_API_BASE_URL}/demandUser/downloadUserExcel`, '_blank');
      }
  
      return {
        columns,
        pagination,
        detail,
        detailVisible,
        formVisible,
        formTitle,
        formData,
        fetchUsers,
        handleDelete,
        handleDetail,
        handleAdd,
        handleEdit,
        handleSubmit,
        setActionRef,
        formRef,
        tagList,
        exportdata
      };
    },
  });
  </script>